package com.ipzoe.common.config;

import com.ipzoe.common.retrofit.service.LeanCloudService;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

/**
 * RetrofitConfiguration
 * <p>
 * Created on 17/3/13.
 *
 * @author xingfinal
 */
@Configuration
public class RetrofitConfiguration {

    @Value("${leancloud.appId}")
    private String leanCloudAppId;

    @Value("${leancloud.appKey}")
    private String leanCloudAppKey;

    @Bean
    public LeanCloudService leanCloudService() {
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    Request original = chain.request();

                    Request request = original.newBuilder()
                            .addHeader("X-LC-Id", leanCloudAppId)
                            .addHeader("Content-Type", "application/json")
                            .build();

                    return chain.proceed(request);
                })
                .addInterceptor(httpLoggingInterceptor)
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .addConverterFactory(JacksonConverterFactory.create())
                .client(okHttpClient)
                .baseUrl("https://api.leancloud.cn/")
                .build();

        return retrofit.create(LeanCloudService.class);
    }

}
